import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import TitleLine from 'components/common/titleLine'
import noImg from 'assets/no_Img.png'
import './index.less';

import EquipmentCheckError from '../component/EquipmentCheckError'
import MaintenanceError from '../component/MaintenanceError'
import tools from '../common/tools'
import FileItem from 'components/common/fileItem'
import CheckPanel from '../component/checkPanel'

import { message, Button } from 'antd'
import ReformModel from './ReformModel'
import ComplaintModel from '../component/ComplaintModel'
import router from 'umi/router'
import { randomString } from 'utils/format'

function RepairDetails ({
    dispatch,
    location,
    location: { query },
    deviceRepair: {repairDetail, process},
    headerTaps: { panes },
}) {
    useEffect(() => {
        // 清空数据
        dispatch({type: 'deviceRepair/clean'})
        dispatch({
          type: 'deviceRepair/getChickDetail',
          payload: { orderId: query.orderId },
        }).then(res => {
            // 改条数据已被其他账号做除删除或其他操作
            if (res.code === '050000') {
                // 关闭当前tabs
                message.error(res.mesg)
                const { pathname } = location
                const panesList = panes.filter(pane => pane.key !== pathname);
                dispatch({
                    type: 'headerTaps/updateHeaderTaps',
                    payload: { panes: panesList },
                });
                router.push('/deviceRepair')
                return
            }
        })
        // 获取节点流程
        dispatch({
            type: 'deviceRepair/getProcess',
            payload: { id: query.procInsId},
        })
    },[dispatch, location, panes, query.orderId, query.procInsId])

    // 更新节点流程
    const getListAgain = () => {
        dispatch({
        type: 'deviceRepair/getProcess',
        payload: { id: query && query.procInsId },
        })
    }

    // 整理维修记录图片和维修参考资料图片数据格式
    // 判断是否为JSON格式
    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }

            } catch(e) {
                return false;
            }
        }
    }

    const[imgArr, setData] = useState([])
    const[imgArr2, setData2] = useState([])

    useEffect(() => {
        if (repairDetail) {
            // 如果是JSON格式才给渲染
            if (isJSON(repairDetail.orderRepairlogFile)) {
                let arr = []
                arr = JSON.parse(repairDetail.orderRepairlogFile)
                setData(arr)
            }
            if (isJSON(repairDetail.file)) {
                let arr = []
                arr = JSON.parse(repairDetail.file)
                setData2(arr)
            }
        }
    }, [repairDetail])

    // 根据报修时间判断是否显示整改按钮： 报修时间七天以内才显示
    const moreThanSevenDays = () => {
        if (repairDetail && repairDetail.reportTime) {
            const nowTime = Date.parse(new Date())
            let reportTime = new Date(repairDetail.reportTime).getTime();
            let day = (nowTime - reportTime)/1000/60/60/24
            if (day < 7) {
                return true
            }
            return false
        }
    }


    // 根据状态来显示隐藏底部按钮
    const shouwButton = (actionId) => {
        switch(Number(actionId)){
            case 2:
                return null// "待企业审批";
            case 3:
                return null // "待平台审核";
            case 4:
                return null // "待接单";
            case 5:
                return (
                <>
                    <Button className='blue-button btnWidth' onClick={() => sureApplication(5, true)}>确认申请</Button>
                    <Button className='orange-button btnWidth' onClick={() => sureApplication(5, false)}>拒绝申请</Button>
                </>
                )// "待确认";
            case 6:
                return null // 待领件
            case 7:
                return null// 待维修
            case 8:
                return null // "维修中";
            case 9: // "待验收";
                return (<>
                <div className="reformModel">
                    <Button className='blue-button btnWidth' onClick={() => goPass(9)}>验收通过</Button>
                </div>
                {
                    repairDetail && repairDetail.rectification && Number(repairDetail.rectification) === 1 && Number(repairDetail.complaint) !== 1
                    ?
                    <ReformModel eformModelConent={eformModelConent}/>
                    :
                    null
                }
                {
                    repairDetail && repairDetail.complaint && Number(repairDetail.complaint) !== 1
                    ?
                    <ComplaintModel complainReson={complainReson}/>
                    :
                    null
                }
                </>)
            case 10:// "已完成";
                return (
                    Number(repairDetail.rectification) === 1
                    ?
                    <ReformModel eformModelConent={eformModelConent}/>
                    :
                    null
                )
            case 11:// "取消中";
                return  null
            case 12: //"超时未完成";
                return (
                    <>
                    {
                        repairDetail && repairDetail.complaint && Number(repairDetail.complaint) !== 1
                        ?
                        <ComplaintModel complainReson={complainReson}/>
                        :
                        null
                    }
                    </>
                )
            case 13:
                return null // "企业审批失败";
            case 14:
                return null // "已删除";
            default:
                return null;
        }
    }
    const { orderId } = query

    // 处理详情页操作按钮的结果
    const processingResults = (res) => {
        if (res.code === '000000') {
            message.success(res.mesg)
        } else {
            message.error(res.mesg)
            // 改条数据已被其他账号做除删除或其他操作
            // if (res.code === '050000') {
            //    // 关闭当前tabs
            //    const { pathname } = location
            //    const panesList = panes.filter(pane => pane.key !== pathname);
            //    dispatch({
            //      type: 'headerTaps/updateHeaderTaps',
            //      payload: { panes: panesList },
            //    });
            //    router.push('/deviceRepair')
            //    return
            // }
        }
        // 详情页数据
        dispatch({
            type: 'deviceRepair/getChickDetail',
            payload: { orderId: query.orderId },
        })
        // 获取节点流程
        dispatch({
            type: 'deviceRepair/getProcess',
            payload: { id: query.procInsId},
        })
    }

    // 确认申请 和 拒绝申请
    const sureApplication = (preStatus, isSure) => {
        dispatch({
            type: 'deviceRepair/getRepairUpdate',
            payload: {
                preStatus,
                orderId: orderId,
                ifPass: isSure,
             },
        }).then(res => {
            processingResults(res)
        })
    }

    // 通过验收
    const goPass = (preStatus) => {
        dispatch({
            type: 'deviceRepair/getRepairUpdate',
            payload: {
                preStatus,
                orderId: orderId,
            },
        }).then(res => {
            processingResults(res)
        })
    }

    // 确认整改
    const eformModelConent = (text, endTime) => {
        dispatch({
            type: 'deviceRepair/getRectionAddComplain',
            payload: {
                orderRectification: {
                    reason: text,
                    endTime
                },
                preStatus: repairDetail.status,
                orderId,
                ifPass: true,
            },
        }).then(res => {
            processingResults(res)
        })
    }

    // 确认投诉
    const complainReson = (reason) => {
        dispatch({
            type: 'deviceRepair/getRectionAddComplain',
            payload: {
                reason,
                preStatus: repairDetail.status,
                orderId: query.orderId,
                ifPass: false,
            },
        }).then(res => {
            processingResults(res)
        })
    }

    return (
        <div className='repairDetails'>
            <div className="aotside_left">
                <div className='boxOne' style={{ marginTop: 0}}>
                    <TitleLine title='维修基本信息'/>
                    <div className='baseInfo'>
                        <div className='baseInfo-body-item'>
                        <span>报修员：</span>
                        <span>{repairDetail && repairDetail.reportName}</span>
                        </div>
                        <div className='baseInfo-body-item'>
                        <span>报修时间：</span>
                        <span>{repairDetail && repairDetail.reportTime}</span>
                        </div>
                        <div className='baseInfo-body-item'>
                        <span>维修时间：</span>
                        <span>{repairDetail && repairDetail.repairCycle}天</span>
                        </div>
                        <div className='baseInfo-body-item'>
                        <span>接单时间：</span>
                        <span>{repairDetail && repairDetail.receiptTime}</span>
                        </div>
                        <div className='baseInfo-body-item' style={{display: 'block'}}>
                        <span>维修期限：</span>
                        <span>{repairDetail && repairDetail.endTime}</span>
                        </div>
                    </div>
                    <div className='messageBox'>
                        <div className='centerBox'>
                            <TitleLine title='维修设备信息' />
                            <div className='centerfoot'>
                                <div className='mesgboxTop'>
                                    <div className='mesgboTop_title' style={{fontSize: '16px', color: '#666'}}>{repairDetail && repairDetail.deviceName}</div>
                                    <div style={{width: '33%', display: 'inline-block'}}>
                                      <span className='create_title'>创建日期</span>
                                      <span className='crate_time'>
                                          {
                                          repairDetail && repairDetail.createTime
                                          ?
                                          repairDetail.createTime.slice(0,10)
                                          :
                                          ''
                                          }
                                      </span>
                                    </div>
                                </div>
                                <div className="contentbox">
                                <div className='imgbox'>
                                    <img src={repairDetail && repairDetail.deviceImage ? repairDetail.deviceImage : noImg} alt=''/>
                                    <div className='imgalt' style={{height: 'initial'}}>
                                        <span>设备状态<span className='imgalText'>{repairDetail && tools.getCheckStatus(repairDetail.runStatus)}</span></span>
                                        <span>台账状态<span className='imgalText'>{repairDetail && tools.getAccountStatus(repairDetail.ledgerStatus)}</span></span>
                                    </div>
                                </div>
                                <div className='mesgbox'>
                                    <div className='otsidebox'>
                                        <div >
                                            <div className='contentbox1'>
                                                <div className='titles'>设备类型</div>
                                                <span className='contents'>{repairDetail && repairDetail.deviceType}</span>
                                            </div>
                                            <div className='contentbox1'>
                                                <div className='titles'>使用部门</div>
                                                <span className='contents'>{repairDetail && repairDetail.groupName}</span>
                                            </div>
                                        </div>
                                        <div >
                                            <div className='contentbox1'>
                                                <div className='titles'>设备编号</div>
                                                <span className='contents'>{repairDetail && repairDetail.deviceNo}</span>
                                            </div>
                                            <div className='contentbox1'>
                                                <div className='titles'>责任人 </div>
                                                <span className='contents'>{repairDetail && repairDetail.chargePerson}</span>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                                </div>
                            </div>
                        </div>
                        <div className='rightBox'>
                            <TitleLine title='维修员信息' />
                            <div className='userMsg'>
                                <div className='photobox'>
                                    <div className='photo'><img src={repairDetail && repairDetail.headImage ? repairDetail.headImage : noImg} alt=''/></div>
                                    <div className='photo_title'>维修员头像</div>
                                </div>
                                <div className='msg'>
                                  <div className="msg-item">
                                    <div className='title'>姓名</div>
                                    <div className='text'>{repairDetail && repairDetail.repairName}</div>
                                  </div>
                                  <div className="msg-item">
                                    <div className='title'>维修员编号</div>
                                    <div className='text'>{repairDetail && repairDetail.userNo}</div>
                                  </div>
                                  <div className="msg-item">
                                    <div className='title'>手机号</div>
                                    <div className='text'>{repairDetail && repairDetail.mobile}</div>
                                  </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <TitleLine title='备品备件' />
                    <span className='contents'>
                        {repairDetail && repairDetail.sparesName ? repairDetail.orderSpareRemark : '无'}
                    </span>
                </div>

                <div className='boxOne'>
                    <TitleLine title='维修结果'/>
                    <div className='boxtitle'>
                        <span className='title' style={{marginLeft: '0.12rem'}}>维修记录：</span>
                        <span className='content'>
                            {repairDetail && repairDetail.orderRepairlogRemark}
                        </span>
                    </div>
                    <div className='imgWrrip' style={{marginTop: '0.2rem'}}>
                    {
                        imgArr.map(item => <FileItem data={item} key={randomString()}/>)
                    }
                    </div>
                </div>

                <div className='boxOne'>
                    <TitleLine title='维修参考资料'/>
                    <div className='boxtitle'>
                        <span className='title' style={{marginLeft: '0.12rem'}}>维修描述：</span>
                        <span className='content'>{repairDetail && repairDetail.repairRemark}</span>
                    </div>
                    <div className='imgWrrip' style={{marginBottom: '0.24rem', marginTop: '0.2rem'}}>
                        {
                            imgArr2.map(item => <FileItem data={item} key={randomString()}/>)
                        }
                    </div>
                    <EquipmentCheckError data={repairDetail}/>
                    <MaintenanceError data={repairDetail}/>
                </div>
                <div className="footerBtns">
                    <div className="btns">
                    {shouwButton(repairDetail && repairDetail.status)}
                    </div>
                </div>
            </div>
            <div className="aotside_right">
                <CheckPanel
                list={process && process.slice(1,process.length)}
                preStatus={query && query.actionId}
                id={repairDetail && repairDetail.orderId}
                procInsId={query.procInsId}
                getListAgain={getListAgain}
                />
            </div>
        </div>
    )
}

export default connect(({ deviceRepair, headerTaps }) => ({
    deviceRepair, headerTaps
}))(RepairDetails)
